﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Alipay.AopSdk.AspnetCore;
using Casamiel.API.Application;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Common.Extensions;
using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NLog;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers
{

    /// <summary>
    /// 
    /// </summary>
    public class AlipayAppletNotifyController : Controller
    {

        private readonly AlipayService _alipayService;
        private readonly IAllPayService _allPayService;
        private readonly IPaymentService _paymentService;
        private readonly IIcApiService _iicApiService;
         

        /// <summary>
        /// 
        /// </summary>
        private readonly NLog.ILogger logger = LogManager.GetLogger("PayService");

        /// <summary>
        /// 
        /// </summary>
        /// <param name="alipayService"></param>
        /// <param name="allPayService"></param>
        /// <param name="paymentService"></param>
        /// <param name="icApiService"></param>
        public AlipayAppletNotifyController(AlipayService alipayService, IAllPayService allPayService,IPaymentService paymentService,
            IIcApiService icApiService)
        {
            _alipayService = alipayService;
            _allPayService = allPayService;
            _paymentService = paymentService;
            _iicApiService = icApiService;
        }

        private Dictionary<string, string> GetRequestPost()
        {
            Dictionary<string, string> sArray = new Dictionary<string, string>();

            ICollection<string> requestItem = Request.Form.Keys;
            foreach (var item in requestItem) {
                sArray.Add(item, Request.Form[item]);

            }
            return sArray;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task Index()
        {
            //Request.EnableRewind();
            /* 实际验证过程建议商户添加以下校验。
			1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
			2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
			3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
			4、验证app_id是否为该商户本身。
			*/
            Dictionary<string, string> sArray = GetRequestPost();
            logger.Trace(JsonConvert.SerializeObject(sArray));
            if (sArray.Count != 0) {
                bool flag = _alipayService.RSACheckV1(sArray);
                if (flag) {
                   
                    //交易状态
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //请务必判断请求时的total_amount与通知时获取的total_fee为一致的
                    //如果有做过处理，不执行商户的业务程序
                    var s = await _allPayService.PayComplete(Request.Form["out_trade_no"], Request.Form["trade_no"], Request.Form["total_amount"].ToDouble(0), Request.Form["app_id"]).ConfigureAwait(false);
                    if (s) {
                        Console.WriteLine(Request.Form["trade_status"]);

                        await Response.WriteAsync("success");
                    }
                    //注意：
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知

                } else {
                    await Response.WriteAsync("fail");
                }
            }
            await Response.WriteAsync("fail");
        }
    }
}
